// 确保导入了所需的模块
const { app, BrowserWindow, ipcMain, dialog, net } = require("electron");
const path = require("path");
const fs = require("fs");
const axios = require("axios");
const FormData = require("form-data");

// 创建一个简单的测试对话框处理程序
ipcMain.handle("test-simple-dialog", async () => {
  console.log("主进程: 测试简单对话框被调用");
  try {
    // 使用最简单的配置
    const result = await dialog.showOpenDialog({
      properties: ["openFile"],
    });
    console.log("主进程: 对话框结果:", result);
    return { success: true, filePaths: result.filePaths };
  } catch (error) {
    console.error("主进程: 对话框错误:", error);
    return { success: false, error: error.message };
  }
});

// 确保在应用程序准备好之后注册所有的IPC处理程序
app.whenReady().then(() => {
  console.log("应用程序准备就绪");

  // 创建窗口等其他初始化代码...

  // 注册上传图片处理程序
  ipcMain.handle("upload-image", async (event, filePath) => {
    try {
      console.log("开始处理文件上传...");

      let selectedFilePath;

      // 如果没有提供文件路径，打开文件选择对话框
      if (!filePath) {
        const result = await dialog.showOpenDialog({
          properties: ["openFile"],
          filters: [
            { name: "所有文件", extensions: ["*"] },
            { name: "文档文件", extensions: ["doc", "docx", "pdf", "txt"] },
            { name: "图片文件", extensions: ["jpg", "jpeg", "png", "gif"] },
          ],
        });

        console.log("文件选择结果:", result);

        if (result.canceled || result.filePaths.length === 0) {
          return { success: false, message: "未选择文件" };
        }

        selectedFilePath = result.filePaths[0];
      } else {
        selectedFilePath = filePath;
      }

      const fileName = path.basename(selectedFilePath);

      // 读取文件内容
      const fileBuffer = fs.readFileSync(selectedFilePath);

      // 构建FormData对象
      const formData = new FormData();
      formData.append("file", new Blob([fileBuffer]), fileName);
      formData.append("attachName", fileName); // 使用文件名作为attachName
      formData.append("attachType", "4");
      formData.append("attachLabel", "1");

      // 生成符合格式的attachCode
      const timestamp = new Date()
        .toISOString()
        .replace(/[-:T.Z]/g, "")
        .substring(0, 17);
      const randomPart = Math.floor(Math.random() * 10000000000000000000)
        .toString()
        .padStart(28, "0");
      const attachCode = `${timestamp}${randomPart}`;

      formData.append("attachCode", attachCode);
      formData.append("orderId", "");
      formData.append("origin", "1");
      formData.append("remark", "");

      // 发送请求上传文件
      const response = await axios.post(
        "http://bsdts.chinaetc.org/ass/order-attach/files",
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
            Cookie: global.cookie || "",
          },
        }
      );

      console.log("文件上传响应:", response.data);

      if (response.data && response.data.status === 0) {
        return {
          success: true,
          fileName: fileName,
          attachCode: attachCode,
        };
      } else {
        return {
          success: false,
          message: response.data?.msg || "上传失败",
        };
      }
    } catch (error) {
      console.error("文件上传错误:", error);
      return {
        success: false,
        message: error.message || "上传失败",
      };
    }
  });

  // 其他IPC处理程序...

  // 确保IPC处理程序在这里注册
  console.log("IPC处理程序已注册");
});

// 在主进程中添加上传Word文档的处理函数
ipcMain.handle("upload-word-document", async () => {
  try {
    const result = await dialog.showOpenDialog({
      properties: ["openFile"],
      filters: [{ name: "Word文档", extensions: ["doc", "docx"] }],
    });

    if (result.canceled || result.filePaths.length === 0) {
      return { success: false, message: "未选择文件" };
    }

    const filePath = result.filePaths[0];
    const fileName = path.basename(filePath);

    // 读取文件内容
    const fileBuffer = fs.readFileSync(filePath);

    // 构建FormData对象
    const formData = new FormData();
    formData.append("file", new Blob([fileBuffer]), fileName);

    // 发送请求上传文件
    const response = await axios.post(
      "https://your-api-endpoint/upload",
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
          Cookie: global.cookie || "",
        },
      }
    );

    if (response.data && response.data.status === 0) {
      return {
        success: true,
        fileName: fileName,
        attachCode: response.data.data.attachCode,
      };
    } else {
      return {
        success: false,
        message: response.data?.msg || "上传失败",
      };
    }
  } catch (error) {
    console.error("上传Word文档失败:", error);
    return {
      success: false,
      message: error.message || "上传Word文档失败",
    };
  }
});

// 在主进程中添加通用文件上传处理函数
ipcMain.handle("upload-file", async () => {
  try {
    const result = await dialog.showOpenDialog({
      properties: ["openFile"],
      filters: [
        { name: "所有文件", extensions: ["*"] },
        { name: "文档文件", extensions: ["doc", "docx", "pdf", "txt"] },
        { name: "图片文件", extensions: ["jpg", "jpeg", "png", "gif"] },
      ],
    });

    if (result.canceled || result.filePaths.length === 0) {
      return { success: false, message: "未选择文件" };
    }

    const filePath = result.filePaths[0];
    const fileName = path.basename(filePath);

    // 读取文件内容
    const fileBuffer = fs.readFileSync(filePath);

    // 构建FormData对象
    const formData = new FormData();
    formData.append("file", new Blob([fileBuffer]), fileName);

    // 发送请求上传文件
    const response = await axios.post(
      "https://api.example.com/upload", // 替换为您的实际上传API
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
          Cookie: global.cookie || "",
        },
      }
    );

    if (response.data && response.data.status === 0) {
      return {
        success: true,
        fileName: fileName,
        attachCode: response.data.data.attachCode,
      };
    } else {
      return {
        success: false,
        message: response.data?.msg || "上传失败",
      };
    }
  } catch (error) {
    console.error("上传文件失败:", error);
    return {
      success: false,
      message: error.message || "上传文件失败",
    };
  }
});

// 在主进程中添加处理函数
ipcMain.handle("upload-file-with-form", async (event, data) => {
  try {
    console.log("主进程: 开始上传文件...");

    // 使用net模块发送请求
    return new Promise((resolve, reject) => {
      const boundary =
        "----WebKitFormBoundary" + Math.random().toString(16).substr(2);

      const request = net.request({
        method: "POST",
        url: "http://bsdts.chinaetc.org/ass/order-attach/files",
        headers: {
          "Content-Type": `multipart/form-data; boundary=${boundary}`,
          Cookie: data.cookie,
        },
      });

      // 构建请求体
      const fileData = data.fileData.split(",")[1]; // 移除Base64前缀
      const fileBuffer = Buffer.from(fileData, "base64");

      // 构建multipart/form-data
      const payload = [];

      // 添加文件
      payload.push(`--${boundary}\r\n`);
      payload.push(
        `Content-Disposition: form-data; name="file"; filename="${data.fileName}"\r\n`
      );
      payload.push(`Content-Type: ${data.fileType}\r\n\r\n`);
      payload.push(fileBuffer);
      payload.push("\r\n");

      // 添加其他字段
      const fields = {
        attachName: data.attachName,
        attachType: data.attachType,
        attachLabel: data.attachLabel,
        attachCode: data.attachCode,
        orderId: data.orderId,
        origin: data.origin,
        remark: data.remark,
      };

      Object.keys(fields).forEach((key) => {
        payload.push(`--${boundary}\r\n`);
        payload.push(`Content-Disposition: form-data; name="${key}"\r\n\r\n`);
        payload.push(`${fields[key]}\r\n`);
      });

      payload.push(`--${boundary}--\r\n`);

      let responseData = "";

      request.on("response", (response) => {
        response.on("data", (chunk) => {
          responseData += chunk;
        });

        response.on("end", () => {
          try {
            const result = JSON.parse(responseData);
            resolve({
              success: true,
              data: result,
            });
          } catch (error) {
            resolve({
              success: false,
              message: "解析响应失败",
            });
          }
        });
      });

      request.on("error", (error) => {
        resolve({
          success: false,
          message: error.message,
        });
      });

      // 写入请求体
      payload.forEach((part) => {
        if (Buffer.isBuffer(part)) {
          request.write(part);
        } else {
          request.write(part);
        }
      });

      request.end();
    });
  } catch (error) {
    return {
      success: false,
      message: error.message,
    };
  }
});

// 修改getAutoLoginCookie处理程序，使用实际的登录凭据
ipcMain.handle("get-auto-login-cookie", async () => {
  try {
    console.log("开始自动登录获取Cookie...");

    // 使用实际的登录凭据
    const response = await axios.post(
      "http://bsdts.chinaetc.org/ass/login",
      {
        username: "实际用户名", // 替换为实际用户名
        password: "实际密码", // 替换为实际密码
      },
      {
        withCredentials: true,
      }
    );

    // 从响应中提取Cookie
    const cookies = response.headers["set-cookie"];
    if (cookies && cookies.length > 0) {
      // 保存Cookie到全局变量，以便其他请求使用
      global.cookie = cookies.join("; ");

      console.log("自动登录成功，已获取Cookie");
      return { success: true, cookie: global.cookie };
    } else {
      console.error("自动登录成功，但未获取到Cookie");
      return { success: false, message: "未获取到Cookie" };
    }
  } catch (error) {
    console.error("自动登录失败:", error);
    return { success: false, message: error.message || "自动登录失败" };
  }
});

// 在主进程中添加上传PDF文件的处理函数
ipcMain.handle("upload-pdf-file", async (event, data) => {
  try {
    console.log("主进程: 开始上传PDF文件...");

    // 将Base64转换为Buffer
    const fileData = data.fileData.split(",")[1]; // 移除Base64前缀
    const fileBuffer = Buffer.from(fileData, "base64");

    // 创建FormData
    const formData = new FormData();
    formData.append("file", new Blob([fileBuffer]), data.fileName);
    formData.append("attachName", data.fileName);
    formData.append("attachType", "4");
    formData.append("attachLabel", "1");
    formData.append("attachCode", data.attachCode);
    formData.append("orderId", "");
    formData.append("origin", "1");
    formData.append("remark", "");

    // 发送请求
    const response = await axios.post(
      "http://bsdts.chinaetc.org/ass/order-attach/files",
      formData,
      {
        headers: {
          Cookie: data.cookie,
          ...formData.getHeaders(),
        },
      }
    );

    return {
      success: true,
      data: response.data,
    };
  } catch (error) {
    console.error("主进程: 上传PDF文件失败:", error);
    return {
      success: false,
      message: error.message || "上传失败",
    };
  }
});

// 添加临时文件处理函数
ipcMain.handle("save-temp-file", async (event, data, fileName) => {
  try {
    const tempDir = path.join(app.getPath("temp"), "app-temp");

    // 确保临时目录存在
    if (!fs.existsSync(tempDir)) {
      fs.mkdirSync(tempDir, { recursive: true });
    }

    const filePath = path.join(tempDir, fileName);
    fs.writeFileSync(filePath, Buffer.from(data));

    return filePath;
  } catch (error) {
    console.error("保存临时文件失败:", error);
    throw error;
  }
});

ipcMain.handle("delete-temp-file", async (event, filePath) => {
  try {
    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath);
    }
    return true;
  } catch (error) {
    console.error("删除临时文件失败:", error);
    return false;
  }
});

// 在创建窗口时添加preload脚本配置
function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: false, // 禁用Node集成
      contextIsolation: true, // 启用上下文隔离
      preload: path.join(__dirname, "../preload.js"), // 确保路径正确
    },
  });

  // 其他窗口配置...
}
